import React, { useEffect, useMemo, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { NavBar, SpinLoading, Toast } from 'antd-mobile';
import { LeftOutline, StarOutline, MessageOutline } from 'antd-mobile-icons';
import { getSickCircleDetail, addSickCircleCollection, cancelSickCircleCollection } from '../../api/sickCircle';
import type { SickCircleDetailResponse } from '../../api/sickCircle';
import './index.css';

const SickCircleDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [detailData, setDetailData] = useState<SickCircleDetailResponse['result'] | null>(null);
  const [error, setError] = useState<string>('');
  const [isCollected, setIsCollected] = useState(false);
  const [collectionLoading, setCollectionLoading] = useState(false);

  // 将后端返回的 picture 字段解析为图片数组，兼容多种格式
  const pictureList = useMemo(() => {
    const raw = detailData?.picture;
    if (!raw) return [] as string[];
    // 如果是 JSON 数组字符串
    try {
      if (raw.trim().startsWith('[')) {
        const arr = JSON.parse(raw) as unknown[];
        return Array.isArray(arr) ? arr.map(String).filter(Boolean) : [];
      }
    } catch {
      // ignore json parse error and fall back to split
    }
    // 常见分隔符兼容：逗号/分号/竖线/空白
    return raw
      .split(/[,;|\s]+/)
      .map(s => s.trim())
      .filter(s => s.length > 0);
  }, [detailData?.picture]);

  useEffect(() => {
    if (id) {
      fetchSickCircleDetail(parseInt(id));
    }
  }, [id]);

  const fetchSickCircleDetail = (sickCircleId: number) => {
    setLoading(true);
    setError('');
    
    getSickCircleDetail({ sickCircleId })
      .then(response => {
        console.log('病友圈详情数据:', response);
        if (response.status === '0000') {
          setDetailData(response.result);
          // 根据返回的collectionFlag设置收藏状态
          setIsCollected(response.result.collectionFlag === 1);
        } else {
          setError(response.message || '获取病友圈详情失败');
        }
      })
      .catch(err => {
        console.error('获取病友圈详情失败:', err);
        setError('网络错误，请稍后重试');
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handleBack = () => {
    navigate(-1);
  };

  const handleCollection = async () => {
    if (!id || collectionLoading) return;
    
    setCollectionLoading(true);
    const sickCircleId = parseInt(id);
    
    try {
      if (isCollected) {
        // 取消收藏
        const response = await cancelSickCircleCollection({ sickCircleId });
        if (response.status === '0000') {
          setIsCollected(false);
          setDetailData(prev => prev ? {
            ...prev,
            collectionNum: Math.max(0, (prev.collectionNum || 0) - 1)
          } : null);
          Toast.show({
            content: '取消收藏成功',
            position: 'center',
          });
        } else {
          Toast.show({
            content: response.message || '取消收藏失败',
            position: 'center',
          });
        }
      } else {
        // 添加收藏
        const response = await addSickCircleCollection({ sickCircleId });
        if (response.status === '0000') {
          setIsCollected(true);
          setDetailData(prev => prev ? {
            ...prev,
            collectionNum: (prev.collectionNum || 0) + 1
          } : null);
          Toast.show({
            content: '收藏成功',
            position: 'center',
          });
        } else {
          Toast.show({
            content: response.message || '收藏失败',
            position: 'center',
          });
        }
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      Toast.show({
        content: '网络错误，请稍后重试',
        position: 'center',
      });
    } finally {
      setCollectionLoading(false);
    }
  };

  const handleComment = () => {
    if (id) {
      navigate(`/pinglun?id=${id}`)
    } else {
      Toast.show({
        content: '未获取到病友圈ID',
        position: 'center',
      })
    }
  };

  if (loading) {
    return (
      <div className="sick-circle-detail-loading">
        <SpinLoading color="primary" />
        <p>加载中...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="sick-circle-detail">
        <NavBar onBack={handleBack}>病友圈详情</NavBar>
        <div className="detail-error">
          <p>{error}</p>
          <button onClick={() => id && fetchSickCircleDetail(parseInt(id))}>重试</button>
        </div>
      </div>
    );
  }

  if (!detailData) {
    return (
      <div className="sick-circle-detail">
        <NavBar onBack={handleBack}>病友圈详情</NavBar>
        <div className="detail-error">
          <p>未找到病友圈详情</p>
        </div>
      </div>
    );
  }

  return (
    <div className="sick-circle-detail">
      <div className="detail-navbar">
        <NavBar onBack={handleBack} backArrow={<LeftOutline />}>
          病友圈详情
        </NavBar>
      </div>
      
      {/* 基本信息 */}
      <div className="detail-header">
        <div className="patient-info">
          {/* <div className="patient-name">张三</div> */}
          <div className="disease-info">
            <span className="disease-label">[病症]</span>
            <span className="disease-name">{detailData.disease || '暂无病症信息'}</span>
          </div>
          <div className="department-info">
            <span className="department-label">[科室]</span>
            <span className="department-name">{detailData.department || '暂无科室信息'}</span>
          </div>
        </div>
      </div>

      {/* 病症详情 */}
      <div className="detail-section">
        <div className="section-title">[病症详情]</div>
        <div className="section-content">
          {detailData.detail || '暂无病症详情'}
        </div>
      </div>

      {/* 治疗经历 */}
      {(detailData.treatmentHospital || detailData.treatmentStartTime || detailData.treatmentProcess) && (
        <div className="detail-section">
          <div className="section-title">[治疗经历]</div>
          <div className="section-content">
            {detailData.treatmentHospital && (
              <div className="treatment-item">
                <span className="treatment-label">医院：</span>
                <span className="treatment-value">{detailData.treatmentHospital}</span>
              </div>
            )}
            {(detailData.treatmentStartTime || detailData.treatmentEndTime) && (
              <div className="treatment-item">
                <span className="treatment-label">治疗时间：</span>
                <span className="treatment-value">
                  {detailData.treatmentStartTime || ''}
                  {detailData.treatmentStartTime && detailData.treatmentEndTime ? ' - ' : ''}
                  {detailData.treatmentEndTime || ''}
                </span>
              </div>
            )}
            {detailData.treatmentProcess && (
              <div className="treatment-item">
                <span className="treatment-label">治疗过程：</span>
                <span className="treatment-value">{detailData.treatmentProcess}</span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 相关图片 */}
      {pictureList.length > 0 && (
        <div className="detail-section">
          <div className="section-title">[相关图片]</div>
          <div className="section-content">
            <div className="images-grid">
              {pictureList.map((url, idx) => (
                <div className="image-container" key={idx}>
                  <img
                    src={url}
                    alt={`相关图片${idx + 1}`}
                    className="detail-image"
                    onError={(e) => {
                      const target = e.currentTarget as HTMLImageElement;
                      target.style.display = 'none';
                      const placeholder = target.nextElementSibling as HTMLElement;
                      if (placeholder) {
                        placeholder.style.display = 'block';
                      }
                    }}
                  />
                  <div className="image-placeholder" style={{ display: 'none' }}>
                    <div className="placeholder-icon">📷</div>
                    <p>图片加载失败</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* 采纳建议 */}
      {detailData.adoptFlag === 1 && detailData.adoptComment && (
        <div className="detail-section">
          <div className="section-title">[采纳建议]</div>
          <div className="section-content">
            <div className="adopt-info">
              {detailData.adoptNickName && (
                <div className="adopt-user">
                  <span className="adopt-label">采纳用户：</span>
                  <span className="adopt-name">{detailData.adoptNickName}</span>
                </div>
              )}
              <div className="adopt-comment">
                <span className="adopt-label">建议内容：</span>
                <span className="adopt-text">{detailData.adoptComment}</span>
              </div>
              {detailData.adoptTime && (
                <div className="adopt-time">
                  <span className="adopt-label">采纳时间：</span>
                  <span className="adopt-date">
                    {new Date(detailData.adoptTime).toLocaleDateString()}
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 底部操作栏 */}
      <div className="detail-actions">
        <div className={`action-item ${collectionLoading ? 'loading' : ''}`} onClick={handleCollection}>
          {collectionLoading ? (
            <SpinLoading color="primary" style={{ fontSize: '16px' }} />
          ) : (
            <StarOutline className={isCollected ? 'active' : ''} />
          )}
          <span>{detailData.collectionNum || 0}</span>
        </div>
        <div className="action-item" onClick={handleComment}>
          <MessageOutline />
          <span>{detailData.commentNum || 0}</span>
        </div>
      </div>
    </div>
  );
};

export default SickCircleDetail;


